package com.czl.common.mvc;//package com.azx.common.mvc;
//
//import com.azx.common.auth.SessionService;
//import com.azx.common.log.LogManger;
//import com.azx.common.log.logger.LoggerFactory;
//import com.azx.common.log.logger.MyLogger;
//import com.azx.common.util.ConverterUtils;
//import com.azx.common.util.SignUtils;
//import com.azx.common.util.Tools;
//import org.apache.commons.lang3.StringUtils;
//import org.aspectj.lang.ProceedingJoinPoint;
//import org.aspectj.lang.Signature;
//import org.aspectj.lang.annotation.Around;
//import org.aspectj.lang.annotation.Aspect;
//import org.aspectj.lang.annotation.Pointcut;
//import org.aspectj.lang.reflect.MethodSignature;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Bean;
//import org.springframework.core.annotation.Order;
//import org.springframework.stereotype.Component;
//import org.springframework.web.context.request.RequestContextHolder;
//import org.springframework.web.context.request.ServletRequestAttributes;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.util.*;
//
//@Aspect
//@Component
//@Order(-10000)
//public class RestApiAop extends BaseRestApiAop {
//
//	private final MyLogger logger = LoggerFactory.createDefaultLogger("restapi_request");
//
//
//	private String extraOrderSourcesParam = "orderSource";
//
//
//	@Autowired
//    private SessionService sessionService;
//
//	@Bean
//	private RestApiAdvice<RestApiResult> getRestApiAdvice() {
//
//		return new RestApiAdvice<RestApiResult>(null) {
//
//			@Override
//			protected RestApiResult createResult(HttpServletRequest request, HttpServletResponse response, Exception e, Integer retCode, String errorMsg) {
//				return RestApiResult.create(retCode, errorMsg);
//			}
//
//			@Override
//			protected void writeLog(HttpServletRequest request, HttpServletResponse response, Exception e,
//                                    Integer retCode, String errorMsg, RestApiResult result) {
//				RestApiAop.this.writeLog(request, null, result, e);
//			}
//		};
//
//	}
//
//    @Pointcut("execution(public * com.azx.cms.modules.*.controller..*.*(..))")
//    public void apiAspect() {
//    }
//
//    @Around("apiAspect()")
//    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
//
//        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        if (attributes == null) {
//            return joinPoint.proceed();
//        }
//
//        HttpServletRequest request = attributes.getRequest();
//        if (request == null) {
//            return joinPoint.proceed();
//        }
//
//        Long time = System.currentTimeMillis();
//        Signature signature = joinPoint.getSignature();
//        MethodSignature methodSignature = ((MethodSignature) signature);
//        RestApi restApi = methodSignature.getMethod().getAnnotation(RestApi.class);
//        Object result = null;
//        Exception ex = null;
//
//        try {
//
//            sessionService.initSession(request);
//
//            if (restApi == null) {
//            	return joinPoint.proceed();
//            }
//
//            if (restApi.innet() && isInnerAddr(request) == false) {
//                return RestApiResult.create(RestApiResult.RetCode.UNAUTH, RestApiResult.RetCode.UNAUTH.getInfo());
//            }
//
////            if(restApi.checkRepeat()){
////                int cycle = restApi.checkRepeatCycle();
////                int max = restApi.checkRepeatMax();
////                String repeatField = restApi.checkRepeatField();
////                Map<String, String[]> parameterMap = request.getParameterMap();
////                String requestURI = request.getRequestURI();
////                if(parameterMap.get(repeatField)==null||parameterMap.get(repeatField).length<=0||StringUtils.isBlank(parameterMap.get(repeatField)[0])){
////                    logger.error("checkRepeat","使用checkRepeat时 请务必设置checkRepeatField");
////                    return RestApiResult.create(RetCode.ILLEGAL, "缺少"+repeatField +"参数","","");
////                }
////                String value = parameterMap.get(repeatField)[0];
////
////
////                String timeStringKey = getTimeStringKey(cycle);
////                int secondNumber = getSecondNumber(cycle);
////
////                if(redisCache.incr("CHECKREPEAT_" +timeStringKey+ requestURI + value, 1,secondNumber)>max){
////                    return RestApiResult.create(RetCode.ILLEGAL, "请求频繁","","",1);
////                }
////            }
////
//            if (restApi.login()) {
//
//                RestApiResult restApiResult = sessionService.initLoginInfo(request);
//                if(restApiResult==null){
//                    return RestApiResult.create(RestApiResult.RetCode.UNAUTH, RestApiResult.RetCode.UNAUTH.getInfo());
//                }else if(restApiResult.getRetCode().intValue()!=1){
//                    return restApiResult;
//                }
//
//            }
//
//            if (restApi.appInfo()){
//
//
//            }
////
////            if (restApi.sign()) {
////                Map<String, String[]> parameterMap = request.getParameterMap();
////
////                String[] debugs = parameterMap.get("__debug");
////                boolean __debug = debugs != null && debugs.length>0 && Tools.toBoolean(debugs[0], false);
////                //只有内网+调试参数 才可以跳过验签
////                if(!__debug&&isInnerAddr(request)){
////                    //检查请求时间
////                    if (!checkTime(parameterMap)) {
////                        return RestApiResult.create(RetCode.ILLEGAL, RetCode.ILLEGAL.getInfo()+",请求时间不合法");
////                    }
////                    //检查是否重放请求
////                    if (!checkRepeatingTime(parameterMap)) {
////                        return RestApiResult.create(RetCode.ILLEGAL, RetCode.ILLEGAL.getInfo()+",禁止重放请求");
////                    }
////
////                    //是否是上传文件
////                    boolean multipartContent = ServletFileUpload.isMultipartContent(request);
////                    Set<String> partNames = Sets.newHashSet();
////                    if(multipartContent){
////                        Collection<Part> parts = request.getParts();
////                        if(parts!=null){
////                            for (Part part : parts) {
////                                String contentType = part.getContentType();
////                                if(contentType!=null){
////                                    String name = part.getName();
////                                    partNames.add(name);
////                                }
////                            }
////                        }
////                    }
////
////                    //检查验签 移除文件相关key
////                    if(!checkSign(parameterMap,partNames)){
////                        return RestApiResult.create(RetCode.ILLEGAL, RetCode.ILLEGAL.getInfo()+",验签不合法");
////                    }
////                }
////            }
//
//            result = joinPoint.proceed();
//            writeOrderSource(request, restApi, result);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            ex = e;
//            result = RestApiResult.create(RestApiResult.RetCode.EXCEPTION, RestApiResult.RetCode.EXCEPTION.getInfo());
//        } finally {
//            sessionService.destroySession();
//            writeLog(request, time, result, ex);
//        }
//
//        return result;
//    }
//
//    protected void writeLog(HttpServletRequest request, Long time, Object result, Exception e) {
//
//    	String logStr = super.getLogStr(request, time, result, e);
//
//    	logger.info(logStr);
//        if(e != null) {
//        	logger.error(e, logStr);
//        } else {
//            logger.debug(logStr, Tools.objectToJsonString(result));
//        }
//    }
//
//    private void writeOrderSource(HttpServletRequest request, RestApi restApi, Object result) {
//
//    	RestApiResult restApiResult = ConverterUtils.simpleCast(result, RestApiResult.class);
//    	if(result == null) {
//    		return;
//    	}
//
//		restApiResult.setOrderSource(getOrderSource(request, restApi.orderSource(), restApi.extOrderSourceParams(), extraOrderSourcesParam));
//    }
//
//
//
//
//
//    //检查时间是否合法时间 超出前后60s为非法时间
//    protected boolean checkTime(Map<String, String[]> parameterMap){
//        String[] api_time_stamps = parameterMap.get("api_time_stamp");
//        if(api_time_stamps==null||api_time_stamps.length<=0||Tools.toLong(api_time_stamps[0],-1)<=0){
//            return false;
//        }
//        long timeStamp = Tools.toLong(api_time_stamps[0]);
//        long nowTime = new Date().getTime();
//        if(timeStamp<nowTime-60000&&timeStamp>nowTime+60000){
//            return false;
//        }
//        return true;
//    }
//
//    //过滤重复请求 重复请求返回false
////    protected boolean checkRepeatingTime(Map<String, String[]> parameterMap){
////        String[] api_signs = parameterMap.get("api_sign");
////        if(api_signs==null||api_signs.length<=0||StringUtils.isBlank(Tools.toString(api_signs[0],""))){
////            return false;
////        }
////        long timeStamp = Tools.toLong(parameterMap.get("api_time_stamp")[0]);
////        String sign = Tools.toString(api_signs[0]);
////        long l = redisCache.sSetAndTime("aopRepeatingTime_" + sign,60*3, timeStamp);
////        if(l<0){
////            return false;
////        }
////        return true;
////    }
//
//
//    protected boolean checkSign(Map<String, String[]> map,Set<String> partNames){
//        String[] signs = map.get("api_sign");
//        if(signs==null||signs.length==0|| StringUtils.isBlank(signs[0])){
//            LogManger.USER_SIGN.info(Tools.JVM(),"RestApiAop.checkSign.null",signs,Tools.objectToJsonString(map));
//            return false;
//        }
//        String sign=signs[0];
//        TreeMap<String, Object> parameterMap = new TreeMap<>();
//        Set<Map.Entry<String, String[]>> entries = map.entrySet();
//        for (Map.Entry<String, String[]> entry : entries) {
//            Object value=entry.getValue()!=null?entry.getValue()[0]:entry;
//            parameterMap.put(entry.getKey(),value);
//        }
//
//        parameterMap.remove("api_sign");
//        for (String partName : partNames) {
//            parameterMap.remove(partName);
//        }
//        String signRet = SignUtils.getSign(parameterMap);
//        boolean check = sign.equals(signRet);
//
//        LogManger.USER_SIGN.info(Tools.JVM(),"RestApiAop.checkSign",check,sign,signRet,Tools.objectToJsonString(map));
//        return check;
//    }
//
//
//    private static String getTimeStringKey(int cycle) {
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(new Date());
//
//        int year = calendar.get(Calendar.YEAR);
//        int month = calendar.get(Calendar.MONTH)+1;
//        int day = calendar.get(Calendar.DATE);
//        int hour = calendar.get(Calendar.HOUR_OF_DAY);
//        int min = calendar.get(Calendar.MINUTE);
//        int s = calendar.get(Calendar.SECOND);
//
//        String key="";
//        switch (cycle){
//            case Calendar.SECOND:{
//                key="_"+s+key;
//
//            }
//            case Calendar.MINUTE:{
//                key="_"+min+key;
//
//            }
//            case Calendar.HOUR_OF_DAY:{
//                key="_"+hour+key;
//
//            }
//            case Calendar.DATE:{
//                key="_"+day+key;
//
//            }
//            case Calendar.MONTH:{
//                key="_"+month+key;
//
//            }
//            case Calendar.YEAR:{
//                key="_"+year+key;
//
//            }
//        }
//        return key;
//    }
//
//
//    private static int getSecondNumber(int cycle) {
//        int number=1;
//        switch (cycle){
//            case Calendar.SECOND:{
//                number*=1;
//            }
//            case Calendar.MINUTE:{
//                number*=60;
//            }
//            case Calendar.HOUR_OF_DAY:{
//                number*=60;
//            }
//            case Calendar.DATE:{
//                number*=24;
//            }
//            case Calendar.MONTH:{
//                number*=30;
//            }
//            case Calendar.YEAR:{
//                number*=12;
//            }
//        }
//        return number;
//    }
//
//
//
//}